package com.authine.cloudpivot.ext.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.GetClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import com.authine.cloudpivot.ext.mapper.OrgUserMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 *
 *
 * @author tangwenting
 */
@Api(value = "专有钉钉接口", tags = "01::EXTAPI::专有钉钉接口")
@RestController
@Validated
@RequestMapping("/api/jsap")
public class JSAPauthentication {
    /**
     * accessKey
     */
    @Value("${syncorg.appKey}")
    private String appKey;

    /**
     * secretKey
     */
    @Value("${syncorg.appSecret}")
    private String appSecret;

    /**
     * domainName
     */
    @Value("${syncorg.domainName}")
    private String domainName;

    // static final String accessKey = "choudpviot-80948K3yR5c303aE3qq";
    // static final String secretKey = "r1Jjd1D30a4PZop1428VNeJ25o4BwiA95zEOww76";
    // static final String domainName = "openplatform.dg-work.cn";
    static final String tokenApi = "/gettoken.json";
    static final String ticketApi = "/get_jsapi_token.json";
    static final String dingtalkAppUserApi = "/rpc/oauth2/dingtalk_app_user.json";
    static String accessToken = "";
    @Autowired
    OrgUserMapper orgUserMapper;

    @ApiOperation("访问专有钉钉-获取JSAPI鉴权")
    @GetMapping({"/get_authentication"})
    public JSONObject getAuthentication() {
        JSONObject data = new JSONObject();
        try {
            accessToken = this.getAccessToken();
            data = getTicket(accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }

    @SuppressWarnings("static-access")
    public String getAccessToken() {
        ExecutableClient executableClient = ExecutableClient.getInstance();
        executableClient.setAccessKey(appKey);
        executableClient.setSecretKey(appSecret);
        executableClient.setDomainName(domainName);
        executableClient.setProtocal("https");
        executableClient.init();
        // executableClient要单例，并且使用前要初始化，只需要初始化一次 61.141.65.29 15899963609_325334 Az168@2020
        // String api = getTokenApi;
        GetClient getClient = executableClient.newGetClient(tokenApi);
        getClient.addParameter("appkey", appKey);
        getClient.addParameter("appsecret", appSecret);
        String apiResult = getClient.get();
        JSONObject inParameter = new JSONObject().parseObject(apiResult);
        String accessToken = inParameter.getJSONObject("content").getJSONObject("data").getString("accessToken");
        return accessToken;
    }

    @SuppressWarnings("static-access")
    public JSONObject getTicket(String accessToken) {
        JSONObject parameter = new JSONObject();
        ExecutableClient executableClient = ExecutableClient.getInstance();
        executableClient.setAccessKey(appKey);
        executableClient.setSecretKey(appSecret);
        executableClient.setDomainName(domainName);
        executableClient.setProtocal("https");
        executableClient.init();
        PostClient postClient = executableClient.newPostClient(ticketApi);
        // 设置参数
        postClient.addParameter("accessToken", accessToken);
        // 调用API
        String apiResult = postClient.post();
        JSONObject inParameter = new JSONObject().parseObject(apiResult);
        String ticketToken = inParameter.getJSONObject("content").getJSONObject("data").getString("accessToken");
        parameter.put("ticketToken", ticketToken);
        return parameter;
    }

    // @ApiOperation("访问专有钉钉-获取用户详情")
    // @PostMapping({"/dingtalk_app_user"})
    // public JSONObject getDingtalkAppUser(@RequestBody JSONObject authCode){
    // accessToken = this.getAccessToken();
    // ExecutableClient executableClient =ExecutableClient.getInstance();
    // executableClient.setAccessKey(accessKey);
    // executableClient.setSecretKey(secretKey);
    // executableClient.setDomainName(domainName);
    // executableClient.setProtocal("https");
    // executableClient.init();
    // //executableClient保证单例
    // IntelligentPostClient intelligentPostClient = executableClient.newIntelligentPostClient(dingtalkAppUserApi);
    // OapiRpcOauth2DingtalkAppUserJsonRequest oapiRpcOauth2DingtalkAppUserJsonRequest = new
    // OapiRpcOauth2DingtalkAppUserJsonRequest();
    // //登录access_token
    // oapiRpcOauth2DingtalkAppUserJsonRequest.setAccess_token(accessToken);
    // //临时授权码
    // oapiRpcOauth2DingtalkAppUserJsonRequest.setAuth_code(authCode.getString("authCode"));
    // //获取结果
    // OapiRpcOauth2DingtalkAppUserJsonResponse apiResult =
    // intelligentPostClient.post(oapiRpcOauth2DingtalkAppUserJsonRequest);
    // JSONObject parameter = new JSONObject().parseObject(apiResult.getContent());
    // JSONObject returnData = new JSONObject();
    // boolean success = parameter.getBooleanValue("success");
    // String referId = "";
    // //String tenantUserId = "";
    // if(success){
    // referId = parameter.getJSONObject("data").getString("referId");
    // //tenantUserId = inParameter.getJSONObject("data").getString("tenantUserId");
    // }else{
    // throw new UserException("获取钉钉用户信息失败");
    // }
    // //String userId = updateUserIdAndUserName(employeeCode,tenantUserId);
    //
    // OrgUser orgUser = new OrgUser();
    // orgUser.setSourceId(referId);
    // orgUser.setUserId(referId);
    // List<OrgUser> users = orgUserMapper.selectByUserId(orgUser);
    // if(users.size()>0){
    // returnData.put("userInfo",users.get(0));
    // returnData.put("success",parameter.getString("parameter"));
    // returnData.put("responseMessage",parameter.getString("responseMessage"));
    // } else {
    // throw new UserException("获取云枢用户信息失败");
    // }
    // return returnData;
    // }

}
